import { deleteFile } from "common/jscloud";
import cell, { setCellOptions } from "../cell";
const {lib, LoadingComponent} = ao2

let descTimmer = null

const isEqual = function(prevProps, nextProps) {
  if (prevProps.src !== nextProps.src) {
    return false
  }
  return true
}

const UploadItemWithDesc = React.memo(function(props={}){
  const context = props.context
  const previewId = props.id
  const textareaId = previewId + '_descript'

  const {url, query, hash, hasQuery} = lib.urlTOquery(props.src)
  const src = url
  const fileId = hash
  const title = query.title || ''

  const removePreview = function(e){
    context.removePreview(previewId)
  }

  const imgButton = context.createImgButton(previewId, {src, removePreview}, function(urls, file){
    context.updatePreview(previewId, urls[0], file[0])
  })

  const textareaConfig = {
    id: textareaId,
    placeholder: '请填写图片描述',
    value: title,
    onChange: function(e){
      let value = e.target.value
      let {url, query, hash} = lib.urlTOquery(props.src)
      query = Object.assign(query, {title: value})
      let tmpsrc = lib.queryTOurl(url, query)
      if (hash) {
        tmpsrc = tmpsrc + '#' + hash
      }
      clearTimeout(descTimmer)
      descTimmer = setTimeout(() => {
        context.updatePreview(previewId, {
          id: previewId,
          src: tmpsrc
        })
      }, 200);
      return true
    }
  }
  const descriptTextarea = <cell.Textarea data={textareaConfig} />

  return (
    <View className="upload-img-with-desc">
      {imgButton}
      {descriptTextarea}
    </View>
  )
}, isEqual)


function UploaderButton(props){
  const data = props.data
  const context = props.context
  const mystore = props.store
  const buttonId = data.id
  const value = data.value
  const imgs = value.split(',')

  const $imgs = imgs.map((src, ii)=>{
    const preivewId = buttonId + '_' + lib.uniqueId()
    return {
      id: preivewId, 
      src,
    }
  })
  const [srcs, setSrcs] = React.useState($imgs)


  const uploadButton = context.createButton('上传', {
    multiple: true
  }, function(urls, files){
    let tmp = []
    urls.forEach((src, ii)=>{
      const preivewId = buttonId + '_' + lib.uniqueId()
      tmp.push({
        id: preivewId, 
        src,
        file: files[ii]
      })
    })
    tmp = srcs.concat(tmp)
    setSrcs(tmp)
  })
  
  context.removePreview = function(id){
    let target = null
    let tmp = srcs.filter((img, ii)=>{
      if (img.id === id) target = img
      return img.id !== id
    })
    let src = target.src
    let {url, query, hash} = lib.urlTOquery(src)
    if (hash) {
      hash = [].concat(hash)
      // Fetcher.post('/api/diskDeleteFile', {
      //   fileid_list: hash
      // })
      deleteFile(hash)
    }
    setSrcs(tmp)
  }

  context.updatePreview = function(id, url, file){
    let tmp = srcs.map((img, ii)=>{
      if (img.id === id) {
        if (typeof url === 'string') {
          img.src = url
        }
        if (lib.isPlainObject(url)) {
          img = Object.assign({}, img, url)
        }
        if (file) {
          img.file = file
        }
      }
      return img
    })
    setSrcs(tmp)
  }

  context.getValue = function(){
    return srcs
    // let tmpValue = ''
    // srcs.forEach((img, ii)=>{
    //   if (ii===srcs.length-1) {
    //     tmpValue += img.src
    //   } else {
    //     tmpValue += img.src + ','
    //   }
    // })
    // return tmpValue
  }

  const previews = srcs.map((imgcfg, ii)=>{
    return <UploadItemWithDesc {...imgcfg} context={context} key={'preview-'+ii}/>
  })

  return (
    <View className="uploader-block">
      {uploadButton}
      <View className="uploader-block-previews">
        {previews}
      </View>
    </View>
  )
}

export default function(){
  setCellOptions('Uploader', {
    template: {
      descript: function(props){
        const upBtton = <UploaderButton data={props} context={this} />
        return <LoadingComponent content={upBtton}/>
      }
    }
  })
}